import { createRouter, createWebHistory } from 'vue-router'
import { userStateStore } from '@/stores/userState'
import axios from 'axios'
import {prompt} from '../publicMethods'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/Window/Window.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    },{
      path: '/video',
      name: 'video',
      component: () => import('../views/video.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.path == '/login' || to.path == '/register') {
      next();
  } else {
      const token = localStorage.getItem('token'); 
      if (token === null || token === '') {
        next('/login');
      } else {
          const userState = userStateStore();
          if(!userState.user.id){
            axios({
              method: 'post',
              url:`${import.meta.env.VITE_API_URL}/api/users/getUserData`,
              headers:{
                "Authorization":token
              }
            }).then(function (response) {
                if(response.data.code){
                  let data = response.data.data;
                  for(let key in data){
                    userState.user[key] = data[key];
                  }
                  next()
                }else{
                  prompt('登陆失效，请重新登陆');
                  next('/login');
                }
            }).catch(function (error) {
                prompt('无法连接服务器，请尝试');
                next('/login');
                console.log(error);
            })
        }else{
          next()
        }
      }
  }
});

export default router